import DomToImage from 'dom-to-image';
import { getQiniuToken, uploadFile } from '../api';
import { dataURLtoFile } from '@/utils';

const uploadImg = async (dataurl: string) => {
    const result:any = await getQiniuToken();
    if(!result || !result.token) {
      return
    }
    const data = new FormData();
    const file = dataURLtoFile(dataurl, `${Date.now()}_flowmix.jpg`);
    data.set('file', file);
    data.set('token', result.token);
  
    const res:any = await uploadFile(data);
    return `${result.domain}/${res.key}`
  }
  
  const dom2image = (dom: HTMLElement) => {
    return DomToImage
        .toJpeg(dom, {
          width: 2 * dom!.offsetWidth,
          height: 2 * dom!.offsetHeight,
          bgcolor: "#fff",
          style: {
            transform: "scale(2)",
            transformOrigin: "top left",
            width: dom?.offsetWidth + "px",
            height: (dom as any).offsetHeight + "px",
          },
          cacheBust: true,
        })
        .then(function(dataurl: string) {
          return uploadImg(dataurl);
        })
        .catch(function(error: any) {
          console.error("oops, something went wrong!", error);
        });
  }

  export default dom2image